<template>
    <nly-content-wrapper class="consignee content-warpper-2" :style="addBtnShow?{'border':'none'}:{}">
        <div class="content-header-2">
            <!--按钮-->
            <div class="btn-wrapper clearfix" :style="addBtnShow?{'border':'none','padding-top':'0','height':'52px' }:{}">
                <a-row class="text-center clearfix">
                    <a-col v-if="addBtnShow" style="text-align:left;line-height:52px;">
                        <a-button @click="AddItem" class="margin-left-10 margin-right-10" type="primary" ghost>
                            <a-icon type="file-add" theme="filled" />新增
                        </a-button>
                        <a-button @click="EditItem()" class="margin-right-10" type="primary" ghost>
                            <a-icon type="edit" theme="filled" />编辑
                        </a-button>
                        <a-button @click="Disable" class="margin-right-10" type="primary" ghost>
                            <a-icon type="delete" theme="filled" />删除
                        </a-button>
                        <!-- <a-button @click="PageList" class="margin-right-10">
                            <a-icon type="file-search" />查询
                        </a-button>
                        <a-button @click="reset" class="margin-right-10">
                            <a-icon type="undo" />重置
                        </a-button> -->
                    </a-col>
                    <a-col v-else :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="addBtnShow">
                            <div class="btns" @click="AddItem">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="editBtnShow">
                            <div class="btns" @click="EditItem()">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">编辑</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="disableBtnShow">
                            <div style="position:relative">
                                <div class="btns" @click="Disable">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                                <div style="position:absolute;width:2px;height:36px;border-radius:6px;background:#ccc;top:0px;right:0px;"></div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="PageList">
                                <a-icon class="btns-icon" type="file-search" />
                                <div class="btns-text">查询</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="reset">
                                <a-icon class="btns-icon" type="undo" />
                                <div class="btns-text">重置</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <nly-row class="col-12">
                <!-- <nly-row class="col-12 ">
                    <nly-col xs="12" sm="12" md="12" lg="9" xl="9" class="form-inline" style="justify-content: left;"></nly-col>
                    <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start" style="justify-content: right;">
                        <nly-button-group>
                            <nly-button variant="info" @click="PageList" button-class="mr-2">查询</nly-button>
                            <nly-button variant="info" button-class="mr-2" @click="reset">重置</nly-button>
                            <nly-button @click="showFunction" variant="info" button-class="mr-2">
                                <i :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />
                                {{ show ? "折叠" : "展开" }}
                            </nly-button>
                        </nly-button-group>
                    </nly-col>
                </nly-row> -->

                <nly-row class="ml-1 mb-2 lr" v-show="show && !addBtnShow">
                    <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline" style="justify-content: left;height:40px;line-height:40px;">
                        <form-input title="客户名称" id="crmName" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.crmName"></form-input>
                        <form-input title="收货人" id="consignee" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.consignee"></form-input>
                        <form-input title="联系电话" id="phone" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.phone"></form-input>
                        <form-input title="手机号码" id="mobile" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.mobile"></form-input>
                        <form-input title="收货地址" id="consigneeAddress" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.consigneeAddress"></form-input>
                        <form-select title="状态" class="ml-2" rightStyle="width:120px;" v-show="false" v-model="postData.status" :dataList="[
                { key: 0, title: '正常' },
                { key: 2, title: '删除' }
              ]"></form-select>
                    </nly-col>
                </nly-row>
            </nly-row>
            <nly-container fluid></nly-container>
        </div>

        <!-- <div>
            <a-button type="primary" class="crm-btn" @click="EditItem()" v-if="editBtnShow">编辑</a-button>
            <a-button type="primary" class="crm-btn" @click="Disable" v-if="disableBtnShow">删除</a-button>
            <a-button type="primary" class="crm-btn" @click="AddItem" v-if="addBtnShow">新增</a-button>
        </div> -->
        <nly-content>
            <!-- 列表 -->
            <a-table :columns="columns" :components="components" :data-source="data" :scroll="{ x:500,y: 500}" bordered :pagination="pagination" @change="onTableChange" :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}">
                <a slot="crmName" slot-scope="text, record" @click="goToDetail(record)" class="goToDetail">
                    {{record.crmName}}
                </a>
                <a slot="formatTitle" slot-scope="text, record" @click="EditItem(record)" class="goToDetail">
                    {{text}}
                </a>
            </a-table>
            <!-- modal 弹窗  -->
            <drag-modal v-model="editModal" lg hide-footer :title="editItem.id ? '编辑收货人信息' : '新增收货人信息'" @cancel="hideModal" class="add-or-edit-modal">
                <div class="min-box" id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" @submit="handleSubmit" style="padding:0">
                        <!-- <div class="line" style="color:#1980Ff;font-size:15px;">基本信息</div> -->
                        <a-row>
                            <a-col :span="24">
                                <a-form-item label="客户名称">
                                    <a-input v-model="editItem.crmName" placeholder="请输入客户名称" read-only />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24" :style="isShow">
                                <a-form-item label="收货人">
                                    <a-input v-decorator="['consignee', { rules: [{ required: true, message: '收货人不能为空' }] }]" placeholder="请输入收货人" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="联系电话">
                                    <a-input placeholder="请输入联系电话" v-model="editItem.phone" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="手机号码">
                                    <a-input placeholder="请输入手机号码" v-model="editItem.mobile" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="收货地址">
                                    <a-input v-model="editItem.consigneeAddress" placeholder="请输入收货地址" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="备注">
                                    <a-textarea placeholder="请输入用户备注" :rows="5" v-model="editItem.remarks" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <template slot="footer">
                    <a-row>
                        <a-col :span="24" :style="{ textAlign: 'right' }">
                            <a-button type="primary" @click="handleSubmit">保存</a-button>
                            <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button>
                            <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                        </a-col>
                    </a-row>
                </template>
            </drag-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { mapState } from "vuex";
import {
    save,
    pageList,
    disable,
    enable,
    deleteConsignee
} from "@/api/crm/consignee";
import { listToMap } from "@/utils/tool/map";
import { components } from "@/utils/antTableComponents";
import Vue from "vue";

export default {
    props: {
        customerId: {
            type: Number,
            default: null
        },
        customer: {
            type: Object,
            default: () => ({})
        }
    },
    data () {
        const columns = [
            {
                title: "收货人",
                dataIndex: "consignee",
                key: "consignee",
                width: 120,
                scopedSlots: { customRender: 'formatTitle' },
            },
            {
                title: "客户名称",
                dataIndex: "crmName",
                key: "crmName",
                width: 120,
                scopedSlots: { customRender: 'crmName' },
            },
            {
                title: "联系电话",
                dataIndex: "phone",
                key: "phone",
                width: 120
            },
            {
                title: "手机号码",
                dataIndex: "mobile",
                key: "mobile",
                width: 120
            },
            {
                title: "收货人地址",
                dataIndex: "consigneeAddress",
                key: "consigneeAddress",
                width: 120
            },
            {
                title: "创建人",
                dataIndex: "createUserName",
                key: "createUserName",
                width: 120
            },
            {
                title: "备注",
                dataIndex: "remarks",
                key: "remarks",
                width: 120
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                width: 120,
                customRender: () => {
                    return "正常";
                }
            }
        ];

        //表格 头部 可伸缩
        this.components = components(columns);
        return {
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------

            //gw 2021年8月16日11:04:08
            visibleSearchPlan: false,
            editModal: false,
            //gw 2021年8月16日11:04:16

            fileList: [],
            basePostData: {},
            postData: {},
            data: [],
            count: 0,
            columns,
            validateStatus: "success",
            isShow: "display:block",
            form: this.$form.createForm(this, { name: "advanced_search" }),
            errorMsg: null,
            isDisabled: false,
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            show: true, //是否显示
            editItem: {}, //新增/编辑对象
            selectedKeys: [],
            selectIds: [],
            selectedData: [],
        };
    },
    created () {
        this.basePostData = {
            current: 1,
            size: 20,
            crmId: this.customerId
        };
        this.postData = { ...this.basePostData };
    },
    mounted () {
        this.PageList();
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
        //是否显示 新增按钮 
        addBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                customerId
                && (permissions.includes("crm:consignee:add")
                    || (crmType == 0 && permissions.includes("crm:clue:consignee:add"))
                    || (crmType == 1 && permissions.includes("crm:potential:consignee:add"))
                    || (crmType == 2 && permissions.includes("crm:deals:consignee:add"))
                )
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 编辑按钮 
        editBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:consignee:edit")
                || (crmType == 0 && permissions.includes("crm:clue:consignee:edit"))
                || (crmType == 1 && permissions.includes("crm:potential:consignee:edit"))
                || (crmType == 2 && permissions.includes("crm:deals:consignee:edit"))
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 删除按钮 
        disableBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:consignee:disable")
                || (crmType == 0 && permissions.includes("crm:clue:consignee:disable"))
                || (crmType == 1 && permissions.includes("crm:potential:consignee:disable"))
                || (crmType == 2 && permissions.includes("crm:deals:consignee:disable"))
            ) {
                isShow = true;
            }
            return isShow;
        },
    },
    methods: {
        //跳转到 客户详情
        goToDetail (item) {
            const { permissions } = this;
            if (!this.customerId && (permissions.includes("crm:potential:edit") || permissions.includes("crm:potential:edit") || permissions.includes("crm:deals:edit"))) {
                this.$router.push(`/crm/customer/detail/${item.crmName}/${item.crmId}/consignee`)
            }
        },
        //添加
        AddItem () {
            const { id, crmName } = this.customer;
            this.editItem = { crmId: id, crmName };
            this.fileList = [];
            this.detailData = [];
            this.editModal = true;
        },
        //编辑
        EditItem (record) {
            const { editBtnShow } = this;
            if (!editBtnShow) {
                return false;
            }
            if (!record) {
                if (this.selectedData.length != 1) {
                    this.$message.warn("请选择一条数据");
                    return false;
                }
                this.editItem = { ...this.selectedData[0] };
            } else {
                this.editItem = { ...record };
            }
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        consignee: this.$form.createFormField({
                            value: this.editItem.consignee
                        })
                    };
                }
            });
            // this.crmName = this.editItem.crmName;
            // this.crmId = this.editItem.crmId;
            this.editModal = true;
        },
        // 获取列表
        PageList () {
            const { postData } = this;
            pageList(postData)
                .then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        this.data = records;
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                })
                .catch(error => { });
        },
        Disable () {
            if (this.selectedKeys.length < 1) {
                this.$message.warn("请选择要删除的发货人");
                return false;
            }
            disable({ ids: this.selectIds.toString() })
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success("删除成功");
                        //刷新 列表
                        this.PageList();
                        this.selectedKeys = [];
                    }
                })
        },
        Enable (item) {
            enable({ ids: this.selectIds.toString() })
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success("启用成功");
                        //刷新 列表
                        this.PageList();
                        this.selectedKeys = [];
                    }
                })

        },
        handleAdd () {
            const { count, detailData } = this;
            const newData = {
                key: count,
                commodityName: "",
                price: "",
                discount: "",
                counts: "",
                specs: "",
                totalPrice: ""
            };
            this.detailData = [...detailData, newData];
            this.count = count + 1;
        },
        //获取
        showFunction () {
            this.show = !this.show;
        },
        showModal (editItem) {
            console.log("editItem", editItem);
            this.editItem = { ...editItem };
            this.editModal = true;
        },
        hideModal () {
            this.editModal = false;
        },
        handleReset () {
            this.form.resetFields();
        },
        handleSubmit (e) {
            e.preventDefault();
            this.form.validateFields((err, values) => {
                this.editItem.crmId = this.customerId;
                this.editItem.crmName = this.customer.crmName;
                this.editItem.consignee = values.consignee;
                console.log("开始保存:", this.editItem);
                if (!err) {
                    save(this.editItem)
                        .then(response => {
                            if (response.code === 200) {
                                this.$message.success("保存成功");
                                //刷新 列表
                                this.PageList();
                                this.hideModal();
                                this.selectedKeys = [];
                            }
                        })

                }
            });
        },
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                current: pagination.current,
                size: pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageList();
        },
        changePageSize (e) {
            const value = e.target.value;
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData, {
                "size": value
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value)
            });
            this.PageList();
        },
        reset () {
            const { basePostData } = this;
            this.postData = { ...basePostData };
        },
        onCellChange (key, dataIndex, value) {
            const dataSource = [...this.detailData];
            const target = dataSource.filter(item => key === item.key)[0];
            if (target) {
                target[dataIndex] = value;
                this.detailData = dataSource;
            }
        },
        selection (keys, info) {
            console.log(info);
            const ids = new Array();
            info.forEach(function (val) {
                ids.push(val.id);
            });
            this.selectIds = ids;
            this.selectedKeys = keys;
            this.selectedData = info;
        },
        //gw 2021年8月16日11:51:51
        cancel () {
            //置空临时查询条件
            // if (this.planActive == 0) {
            //     setTimeout(() => {
            //         this.onOffDefineFields.forEach(item => {
            //             item.value = '';
            //         });
            //     }, 200)
            // }
            this.visibleSearchPlan = false;
        },
        onShowSerch () {
            this.visibleSearchPlan = true;
        },
    },
    watch: {
        "customerId": function (n, o) {
            console.log("consignee_客户ID改变:", n, o);
            const { basePostData } = this;
            basePostData.crmId = n;
            this.reset();
            this.PageList();
            this.selectedKeys = [];
        }
    }
};
</script>
<style lang="less">
    .consignee {
        //   .form-inline label {
        //     justify-content: left !important;
        //   }
        .form-inline > .col {
            margin-bottom: 1.5rem !important;
        }
        .ant-advanced-search-form {
            padding: 24px;
            background: #fbfbfb;
        }

        .ant-advanced-search-form .ant-form-item-control-wrapper {
            flex: 1;
        }

        #components-form-demo-advanced-search .ant-form {
            max-width: none;
        }
        #components-form-demo-advanced-search .search-result-list {
            margin-top: 16px;
            background-color: #fafafa;
            min-height: 200px;
            text-align: center;
            padding-top: 80px;
        }

        .ant-popover-inner {
            z-index: 2999;
        }
    }
    .ant-advanced-search-form .ant-form-item {
        display: flex;
        margin-bottom: 0px !important;
    }
    @import '~@/style/crm.less';
</style>
